package ctrl

import (
	"encoding/json"
	"errors"
	"gin_zebra/app/dao"
	"gin_zebra/app/dto"
	"gin_zebra/app/middleware"
	"gin_zebra/public"
	"gitee.com/xiedongji/go-core/lib"
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
	"time"
)

type UserUnAuthController struct{}

//注册路由器
func UserUnAuthRegister(router *gin.RouterGroup) {
	ctrl := &UserController{}
	router.POST("/login", ctrl.Login)
	router.POST("/reg", ctrl.Reg)
}

func (ctrl *UserController) Login(ctx *gin.Context) {
	params := &dto.UserLoginInput{}
	if err := params.BindValidParams(ctx); err != nil {
		middleware.ResponseError(ctx, err)
		return
	}

	db, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(ctx, err)
		return
	}

	//获取用户信息
	user := &dao.User{}
	user, err = user.LoginCheck(ctx, db, params)
	if err != nil {
		middleware.ResponseError(ctx, err)
		return
	}

	writeSession(ctx, &dto.UserSession{Id: user.Id, Username: user.Username, LoginTime: time.Now()})

	out := &dto.UserLoginOutput{Nickname: user.Nickname, Username: user.Username, Token: "adfasdfadf"}
	middleware.ResponseSuccess(ctx, "登录成功", out)

}

func (ctrl *UserController) Reg(ctx *gin.Context) {
	params := &dto.UserRegInput{}
	if err := params.BindValidParams(ctx); err != nil {
		middleware.ResponseError(ctx, err)
		return
	}

	db := lib.GORMDefaultPool
	//检查用户名是否存在
	user := &dao.UserReg{Username: params.UserName}
	if _, err := user.Find(ctx, db, user); err == nil {
		middleware.ResponseError(ctx, errors.New("该用户名已经存在,请重新输入"))
		return
	}
	//开始 注册 用户
	salt := public.RandomString(6)
	pwd := public.GenSaltPassword(salt, params.Password)

	user.Password = pwd
	user.Salt = salt
	user.AddTime = time.Now().Unix()
	user.ModTime = time.Now().Unix()

	//dbTool := core.GORMDefaultPool
	if err := user.Save(ctx, lib.GORMDefaultPool); err != nil {
		middleware.ResponseError(ctx, err)
		return
	}

	writeSession(ctx, &dto.UserSession{Id: user.Id, Username: user.Username, LoginTime: time.Now()})

	out := &dto.UserLoginOutput{Nickname: "", Username: user.Username, Token: "adfasdfadf"}
	middleware.ResponseSuccess(ctx, "注册成功", out)
	return
}

//写入session
func writeSession(ctx *gin.Context, userSession *dto.UserSession) error {
	str, err := json.Marshal(userSession)
	if err != nil {
		return err
	}
	sess := sessions.Default(ctx)
	sess.Set(public.SessionUserKey, string(str))
	sess.Save()
	return nil
}
